package pers.cz.node;


import pers.cz.annotation.AutoRegister;
import pers.cz.flowcell.JefFlowCell;
import pers.cz.mxgraph.MxElement;
import pers.cz.utils.ThreadUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: Reids
 * @description: 抽象节点
 * 节点应具有的方法：
 * 1、校验节点的合法性
 * 2、获取节点的参数
 * 3、判断节点的状态
 * 4、执行节点并通知前端
 * 5、获取执行结果
 * 6、
 * @author: Cheng Zhi
 * @create: 2023-01-08 19:43
 **/
@AutoRegister
public abstract class AbstractNode implements Node {

    public JefFlowCell jefFlowCell;

    private Runnable runnable;

    /**
     * 自定义业务参数传递
     */
    public Map<String, Object> map = new ConcurrentHashMap<String, Object>();

    public AbstractNode(JefFlowCell jefFlowCell) {
        this.jefFlowCell = jefFlowCell;
    }

    // 支持动态扩展
    public void run(NodeCallBack callBack) {
        map.put(NodeRunState.RUN_TYPE, NodeRunState.RUN_SUCCESS); // 默认运行状态为成功。
        try {
            verify();
            runNode(callBack);
            map.put(NodeRunState.RUN_TYPE, NodeRunState.RUN_SUCCESS);
            //MessagePushSocketUtils.sendMsg(MessagePushSocketUtils.AUTOUI_MESSAGE, mxCell.getId() + "|" + NodeRunState.NODE_TYPE_SUCCESS, 0);
        } catch (Exception e) {
            e.printStackTrace();
            //MessagePushSocketUtils.sendMsg(MessagePushSocketUtils.AUTOUI_MESSAGE, mxCell.getId() + "|" + NodeRunState.NODE_TYPE_FAIL, 0);
            map.put(NodeRunState.RUN_TYPE, NodeRunState.RUN_FAIL);
        }
        callBack.callBack(map);
        // 每个节点运行完成后默认休眠一段事件
        sleep();
    }

    public abstract void runNode(NodeCallBack callBack) throws Exception;
    /**
     * 检验参数
     */
    public abstract void verify() throws Exception;

    public void sleep() {
        sleep(10000L);
    }

    public void sleep(Long millis) {
        ThreadUtils.doSleep(millis);
    }

    public String getName() {
        return jefFlowCell.getName();
    }

}
